<?php
namespace app\models;

use app\models\BaseModel;
use app\enum\EnumOther;
use app\dao\ProductDAO;
use app\dao\ProductImageDAO;
use Yii;
use app\controllers\StockPileController;
use app\dao\StockPileDAO;
use app\dao\ProductUnitDAO;
use app\dao\UnitDAO;
use app\enum\EnumOriginType;
use app\helpers\storeTokenTool;
use app\helpers\scmTokenTool;
use app\helpers\Curl;
use app\dao\ProductExtendDAO;

class ProductModel extends BaseModel
{
	/**
	 * @desc覆盖父方法返回对象
	 * @author liaojianwen
	 * @date 2016-12-05
	 * @return ProductModel
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @desc 产品列表
	 * @author liaojianwen
	 * @date 2016-12-05
	 */
	public function getProductList($pageInfo, $cond = null)
	{
		if (empty ( $pageInfo )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$result = ProductDAO::getInstance ()->getProductList ( $pageInfo, $cond );
		if (! $result) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'no data found' );
		}
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	
	/**
	 * @desc 保存商品
	 * @author liaojianwen
	 * @date 2016-12-07
	 */
	public function saveProduct($productInfo)
	{
		if (empty ( $productInfo )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$tr = Yii::$app->db->beginTransaction ();
		try {
			$product = [ 
					'product_name' => $productInfo ['product_name'],
					'category_id' => $productInfo ['category_id'],
					'supplier_id' => $productInfo ['supplier_id'],
					'quantity_unit' => $productInfo ['quantity_unit'],
					'product_img' => $productInfo ['product_img'],
					'description' => $productInfo ['description'],
					'warn_quantity' => $productInfo ['warn_quantity'], 
					'price' => $productInfo['price'],
					'warehouse_id' => $productInfo['warehouse_id'],
					'supply_price' => $productInfo['supply_price'],
					'guide_price' => $productInfo['guide_price'],
					'barcode' => $productInfo['barcode'],
				    'produced_time' => !empty($productInfo['produced_time']) ? strtotime($productInfo['produced_time']) : 0,
				    'quality_time' => !empty($productInfo['quality_time']) ? strtotime($productInfo['quality_time']) : 0,
				    'sync_store' => $productInfo['sync_store'],
				    'sync_shop' => $productInfo['sync_shop'],
			];
			if($productInfo['product_id']){
				//编辑
				$product_update = ProductDAO::getInstance()->iupdate($product, "product_id = :id", [':id'=>$productInfo['product_id']]);
				if(!$product_update){
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update product fail');
				}
				//
				$condition ="product_id =:pid and warehouse_id =:wid";
				$params = [
						':pid'=>$productInfo['product_id'],
						':wid'=> $productInfo['warehouse_id'],
				];
				$ret = StockPileDAO::getInstance ()->iselect ( "stock_pile_id,quantity_unit,quantity", $condition, $params,'one');
				if ($ret){
					if(($ret['quantity_unit'] <> $productInfo ['quantity_unit'])){
						if($ret['quantity'] == 0){
							$cond ="product_id =:pid and warehouse_id =:wid";
							$par = [
									':pid'=>$productInfo['product_id'],
									':wid'=> $productInfo['warehouse_id'],
							];
							$retu = StockPileDAO::getInstance ()->ireplaceinto ( [ 
									'quantity_unit' => $productInfo ['quantity_unit'] ,
									'warehouse_id' => $productInfo['warehouse_id']
							], $cond, $par);
							if(!$retu){
								$tr->rollBack();
								$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile failed');
							}
						} else {
							$tr->rollBack();
							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','remove the left quantity');
						}
					}
				} else {
					//添加到stock_pile
					StockPileDAO::getInstance()->InsertStockPile($productInfo['product_id'],$productInfo['warehouse_id']);
				}
				
				$product_id = $productInfo['product_id'];
			} else{
				//新增
				$product_id = ProductDAO::getInstance ()->iinsert ( $product, true );
				if ($product_id) {
					$sn = EnumOther::SN_PREFIX . str_repeat ( '0', 6 - strlen ( $product_id ) ) . $product_id;
				
					$product_sn = ProductDAO::getInstance ()->iupdate ( [
							'product_sn' => $sn
					], "product_id=:id", [
							':id' => $product_id
					] );
					if (! $product_sn) {
						$tr->rollBack ();
						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update sn fail' );
					}
					//添加到stock_pile
					StockPileDAO::getInstance()->InsertStockPile($product_id,$productInfo['warehouse_id']);
				} else {
					$tr->rollBack ();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save product fail' );
				}
			}
			//基本单位（辅助单位表）
			$columns = [
				'unit' =>$productInfo ['quantity_unit'],
				'product_id'=>$product_id,
			];
			$conditions = "product_id = :pid and delete_flag=:flag and unit_type = :type";
			$params = [
				':pid'=>$product_id,
				':flag'=> EnumOther::NO_DELETE,
				':type'=>0,
			];
			$res_unit = ProductUnitDAO::getInstance()->ireplaceinto($columns, $conditions, $params,true);
			if(!$res_unit){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product_unit update fail');
			}
			
			//init unit_content
			$res_unit = $this->InitUnitContent ( $product_id );
			if (! $res_unit) {
				$tr->rollBack ();
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'init unit_content fail' );
			}
			
			//更新stock_pile 的quantity_unit
			$conditions ="product_id =:pid and warehouse_id =:wid";
			$params = [
					':pid'=>$productInfo['product_id'],
					':wid'=> $productInfo['warehouse_id'],
			];
			$stock_unit = StockPileDAO::getInstance()->iselect("quantity_unit,stock_pile_id",$conditions,$params,'all');
			foreach($stock_unit as $tmp){
				if(!$tmp['quantity_unit']){
					$reu = StockPileDAO::getInstance()->iupdate(['quantity_unit'=>$productInfo['quantity_unit']], "stock_pile_id =:sid", [':sid'=>$tmp['stock_pile_id']]);
					if(!$reu){
						$tr->rollBack();
						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'stock_pile  update  quantity_unit fail');
					}
				}
			}
			
			// 图片
			if (isset ( $productInfo ['pics'] ) && !empty( $productInfo ['pics'])) {
				$pics = explode ( ',', $productInfo ['pics'] );
				foreach ( $pics as $img ) {
					$img = trim($img);
					$field = [ 
							'product_id' => $product_id,
							'origin_img' => $img,
							'delete_flag'=>EnumOther::NO_DELETE,
					];
					$imgs = ProductImageDAO::getInstance()->iselect("image_id", "product_id =:id and origin_img =:img and delete_flag=:flag", [
							':id'=>$product_id,
							':img'=>$img,
							':flag'=>EnumOther::NO_DELETE,
					]);
					if($imgs){
						//更新 先把全部删掉在更新回去
						$img_update = ProductImageDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED],  "product_id =:id", [
								':id'=>$product_id,
						]);
						if(!$img_update){
							$tr->rollBack();
							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','update img delete fail');
						}
					}
// 					$image = ProductImageDAO::getInstance ()->iinsert ( $field );
					$image = ProductImageDAO::getInstance()->ireplaceinto($field,  "product_id =:id and origin_img =:img", [
								':id'=>$product_id,
								':img'=>$img,
						]);
					if (! $image) {
						$tr->rollBack ();
						return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','save image fail');
					}
				}
			}
			
			$tr->commit ();
			
			// 同步商品到店铺
			if ($product['sync_store'])
			{
				$this->InitStoreGoods($product_id);
			}
			
			// 同步商品到商城
			if ($product['sync_shop'])
			{
				$result = $this->InitShopGoods($product_id);
				if (is_numeric($result) && $result)
				{
					ProductDAO::getInstance()->iupdate(['good_id'=>$result], "product_id = :id", [':id'=>$product_id]);
				}
			}
			
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		} catch ( \Exception $e ) {
			$tr->rollBack ();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
		}
	}
	
	/**
	 * @desc 获取编辑页面数据
	 * @author liaojianwen
	 * @date 2016-12-08
	 */
	public function getProductEdit($id)
	{
		if(empty($id)){
			return false;
		}
		
		$result = ProductDAO::getInstance()->getProductEdit($id);
		if(empty($result)){
			return false;
		}
		return $result;
	}
	
	/**
	 * @desc 删除商品
	 * @author liajianwen
	 * @date 2016-12-09
	 */
	public function delProduct($ids) 
	{
		if(empty($ids)) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$tr = Yii::$app->db->beginTransaction ();
		try {
			$_ids = explode ( ',', $ids );
			$coloumns = [
				'delete_flag' => EnumOther::DELETED,
			];
			foreach ( $_ids as $id ) {
				$conditions = "product_id =:id";
				$params = [
					':id'=>$id,
				];
				$result = ProductDAO::getInstance ()->iupdate ( $coloumns, $conditions, $params);
				if (! $result) {
					$tr->rollBack();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'del product fail' );
				}
				
				$count = ProductImageDAO::getInstance()->iselect("image_id", "product_id =:id and delete_flag =:flag", [
						':id'=>$id,
						':flag' =>EnumOther::NO_DELETE,
				]);
				if($count){
					$img = ProductImageDAO::getInstance()->iupdate( $coloumns, $conditions, $params);
					if(! $img){
						$tr->rollBack();
						return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del img fail');
					}
				}
			}
			$tr->commit();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		} catch ( \Exception $e ) {
			$tr->rollBack();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
		}
	}

	/**
	 * @desc 获取库存信息
	 * @param $cond 查询条件
	 * @param $pageInfo 页面信息
	 * @author liaojianwen
	 * @date 2016-12-22
	 */
	public function getStockPile($condition, $filter, $pageInfo)
	{
		if(empty($pageInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','pageinfo is empty');
		}
		
		$result = ProductDAO::getInstance()->getStockPile($condition, $filter, $pageInfo);
		foreach($result['list'] as &$pp){
			$auth = Yii::$app->authManager;
			$userId = Yii::$app->user->id;
			$res = $auth->checkAccess($userId, EnumOther::CHECK_PRODUCT_PRICE);
			if(!$res){
				$pp['price'] = 0;
			}
		}
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
	}
	
	/**
	 * @desc 保存商品关联的多单位管理
	 * @param $units 单位信息
	 * @param $remove 删除单位信息
	 * @param $product_id 商品id
	 * @author liaojianwen
	 * @date 2017-02-15
	 */
	public function saveProductUnit($units, $remove, $product_id)
	{
		if (empty ( $units )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'units is empty' );
		}
		//清掉为空的元素
		foreach ($units as $k=> $det){
			foreach ($det as $j => $deet){
				if(empty($deet)){
					unset($units[$k][$j]);
				}
			}
		}
		// 表头信息
		$tr = Yii::$app->db->beginTransaction();
		try{
			//删除的单位
			foreach ($remove as $move){
				$res_remove = ProductUnitDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "product_unit_id = :det_id", [':det_id'=>$move['product_unit_id']]);
				if(!$res_remove){
					$tr->rollBack();
					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove product_unit_id:'+$move['product_unit_id'] +'failed');
				}
			}
			foreach ( $units as &$det ) {
				$cond_det = "product_unit_id = :id";
				$param_det = [
						':id' => isset($det ['product_unit_id'])?$det['product_unit_id']:0,
				];
				$res_det = ProductUnitDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
				if (! $res_det) {
					$tr->rollBack();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save product_unit failure' );
				}
				
				if(!isset($det['unit_type'])){
						// unit_type == 0 被清掉了 基本单位
					$res_unit = ProductDAO::getInstance ()->findByAttributes ( [ 
							'product_id' 
					], "product_id = :pid and quantity_unit =:unit", [ 
							':pid' => $product_id,
							':unit' => $det ['unit'] 
					] );
					if (! $res_unit) {
						$res_pro = ProductDAO::getInstance ()->iupdate ( [ 
								'quantity_unit' => $det ['unit'] 
						], "product_id = :pid and delete_flag = :flag", [ 
								':pid' => $product_id,
								':flag' => EnumOther::NO_DELETE 
						] );
						if(!$res_pro){
							$tr->rollBack();
							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity_unit failure' );
						}
						//更新分仓
						$res_pro = StockPileDAO::getInstance ()->iupdate ( [
								'quantity_unit' => $det ['unit']
						], "product_id = :pid and delete_flag = :flag", [
								':pid' => $product_id,
								':flag' => EnumOther::NO_DELETE
						] );
						if(!$res_pro){
							$tr->rollBack();
							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update stock_pile quantity_unit failure' );
						}
					}
				}
			}
			//把单位关系更新到product
			$res_units = ProductUnitDAO::getInstance()->getUnits($product_id);
			if($res_units){
				$pre_unit = '';
				$units_content = '';
				foreach($res_units as $key => $unit){
					if($key == 0){
						$pre_unit = $unit['rate'];
						$units_content .= '1'. $unit['unit_name'].'=';
					} else {
						$units_content .= $pre_unit/$unit['rate'] . $unit['unit_name'] .'=';
					}
				}
				$units_content = substr($units_content, 0,strlen($units_content) - 1 );
				$res_update_unit = ProductDAO::getInstance()->iupdate(['unit_content'=>$units_content], "product_id = :pro_id", [':pro_id'=>$product_id]);
				if(!$res_update_unit){
					$tr->rollBack();
					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update product:'+$product_id+' unit_content failed');
				}
			} else {
				$tr->rollBack();
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select product_unit failure' );
			}
			///更新到store
			$res_store_unit = $this->SyncGoodsUnit($product_id);
			if($res_store_unit != 'true'){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'store unit sync fail');
			}
			
			$tr->commit();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		}catch (\Exception $e){
			$tr->rollBack();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
		}
	}
	
	/**
	 * @desc  根据id获取辅助单位
	 * @author liaojianwen
	 * @date 2017-01-17
	 */
	public function getProductUnitInfo($id)
	{
		if(empty($id)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', ' id is empty');
		}
		$result = ProductUnitDAO::getInstance()->getProductUnitInfo($id);
		if(!$result){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}
	
	/**
	 * @desc 获取 库存信息
	 * @author liaojianwen
	 * @date 2017-03-13
	 */
	public function getProductStock($condition)
	{
		foreach ($condition as $key=> $det){
			if(empty($det) || $det =='undefined'){
				unset($condition[$key]);
			}
		}
		$result = ProductDAO::getInstance()->getProductStock($condition);
		return $result;
	}
	
	/**
	 * @desc 初始化商品的单位关系
	 * @author liaojianwen
	 * @date 2017-03-20
	 */
	private  function InitUnitContent($product_id)
	{
		$tr = Yii::$app->db->beginTransaction();
		try {
			$fields =[
					'product_id',
					'rate',
					'unit_name',
			];
			$conditions = "p.delete_flag = :flag and p.product_id = :pid";
			$params = [
					':flag'=>EnumOther::NO_DELETE,
					':pid'=> $product_id,
			];
			$joinArray = [
					[
							'unit u',
							'u.unit_id =p.unit',
							'left' => ''
					]
			];
			$res_units = ProductUnitDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', "rate DESC", $joinArray, 'p' );
			$pre_unit = '';
			$units_content = '';
			foreach ( $res_units as $key => $unit ) {
				if ($key == 0) {
					$pre_unit = $unit ['rate'];
					$units_content .= '1' . $unit ['unit_name'] . '=';
				} else {
					$units_content .= $pre_unit / $unit ['rate'] . $unit ['unit_name'] . '=';
				}
			}
			$units_content = substr ( $units_content, 0, strlen ( $units_content ) - 1 );
	
			$res = ProductDAO::getInstance()->iupdate(['unit_content'=>$units_content], 'product_id=:pid', [':pid'=>$product_id]);
			if($res === false){
				$tr->rollBack();
				return false;
			}
			$tr->commit();
			return true;
		}catch (\Exception $e){
			$tr->rollBack();
			return false;
		}
	}
	
	/**
	 * @desc 导出采购统计（供应商）
	 * @author liaojianwen
	 * @date 2017-03-10
	 */
	public function exportProductStock($purchaseInfo, $filename, $title, $excVer = "xls")
	{
		$data = $purchaseInfo;
		$objPHPExecl = new \PHPExcel();
		$objSheet = $objPHPExecl->getActiveSheet();
		$objWriter = NULL;
		// 创建文件格式写入对象实例
		switch ($excVer){
			case 'xlsx':
				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
				break;
			case 'xls':
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
				break;
			default:
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
		}
		//设置宽度
		$objSheet->mergeCells("A1:E2");
		$objSheet->setCellValue("A1", $title);
		$objSheet->getStyle('A1')->getFont()->setSize(26);
		$objSheet->getStyle('A1')->getFont()->setBold(true);
		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			
		$objSheet->getColumnDimension('A')->setWidth(20);
		$objSheet->getColumnDimension('B')->setWidth(20);
		$objSheet->getColumnDimension('C')->setWidth(20);
		$objSheet->getColumnDimension('D')->setWidth(20);
		$objSheet->getColumnDimension('E')->setWidth(20);
		
		$objSheet->setCellValue('A3', '供应商');
		$objSheet->getStyle('A3')->getFont()->setBold(true);
		$objSheet->setCellValue('B3', '类目');
		$objSheet->getStyle('B3')->getFont()->setBold(true);
		$objSheet->setCellValue('C3', '产品名称');
		$objSheet->getStyle('C3')->getFont()->setBold(true);
		$objSheet->setCellValue('D3', '单位');
		$objSheet->getStyle('D3')->getFont()->setBold(true);
		$objSheet->setCellValue('E3', '数量');
		$objSheet->getStyle('E3')->getFont()->setBold(true);
	
		$rowNum = 4;
		foreach($data as $det){
			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $det['supplier_name'], false);
			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['category_name'], false);
			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['product_name'], false);
			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['unit_name'], false);
			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['quantity'], false);
	
			$rowNum++;
		}
			
		ob_end_clean(); // 去掉缓存
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		$objWriter->save('php://output');
	}
	
	/**
	 * @desc 商城新增商品添加到scm
	 * @author liaojianwen
	 * @date 2017-03-21
	 */
	public function shopInsertProduct($data)
	{
	
		$productInfo = $data['data'];
		if (empty ( $productInfo )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$tr = Yii::$app->db->beginTransaction ();
		try {
			$unit = UnitDAO::getInstance()->iselect('unit_name', "unit_id = :id", [':id'=>$productInfo ['goods_unit']],'one');
			if(empty($unit)){
				$units_content = '';
			} else {
				$units_content = '1' . $unit ['unit_name'];
			}
			$product = [
					'product_name' => $productInfo ['goods_name'],
					'category_id' => $productInfo ['cat_id'],
					'supplier_id' => $productInfo ['supplier_id'],
					'quantity_unit' => $productInfo ['goods_unit'],
					'warehouse_id' => EnumOther::DEFAULT_WARE, // @todo 线上要改
					'good_id' => $productInfo ['good_id'],
					'attr_id' => $productInfo ['attr_id'] ,
					'unit_content' =>$units_content,
			];
			$res_pro = ProductDAO::getInstance()->iselect("product_id", "good_id = :gid and attr_id = :aid", [':gid'=>$productInfo['good_id'],':aid'=>$productInfo['attr_id']]);
			if($res_pro){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','exists product');
			}
			// 新增
			$product_id = ProductDAO::getInstance ()->iinsert ( $product, true );
			if ($product_id) {
				$sn = EnumOther::SN_PREFIX . str_repeat ( '0', 6 - strlen ( $product_id ) ) . $product_id;
				
				$product_sn = ProductDAO::getInstance ()->iupdate ( [ 
						'product_sn' => $sn 
				], "product_id=:id", [ 
						':id' => $product_id 
				] );
				if (! $product_sn) {
					$tr->rollBack ();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update sn fail' );
				}
				// 添加到stock_pile
				StockPileDAO::getInstance ()->InsertStockPile ( $product_id, EnumOther::DEFAULT_WARE );
			} else {
				$tr->rollBack ();
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save product fail' );
			}
			//基本单位（辅助单位表）
			$columns = [
					'unit' =>$productInfo ['goods_unit'],
					'product_id'=>$product_id,
			];
			$conditions = "product_id = :pid and delete_flag=:flag and unit_type = :type";
			$params = [
					':pid'=>$product_id,
					':flag'=> EnumOther::NO_DELETE,
					':type'=>0,
			];
			$res_unit = ProductUnitDAO::getInstance()->ireplaceinto($columns, $conditions, $params,true);
			if(!$res_unit){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product_unit update fail');
			}
			
			$tr->commit ();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		} catch ( \Exception $e ) {
			$tr->rollBack ();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
		}
	}
	
	/**
	 * @desc 获取商品导出数据
	 * @author liaojianwen
	 * @date 2017-05-08
	 */
	public function getExplodeProduct($condition)
	{
		foreach ($condition as $key=> $det){
			if(empty($det) || $det =='undefined'){
				unset($condition[$key]);
			}
		}
		$result = ProductDAO::getInstance()->getExplodeProduct($condition);
		return $result;
	}
	
	/**
	 * @desc 导出采购统计（供应商）
	 * @author liaojianwen
	 * @date 2017-03-10
	 */
	public function exportProductList($productInfo, $filename, $title, $excVer = "xls")
	{
		$data = $productInfo;
		$objPHPExecl = new \PHPExcel();
		$objSheet = $objPHPExecl->getActiveSheet();
		$objWriter = NULL;
		// 创建文件格式写入对象实例
		switch ($excVer){
			case 'xlsx':
				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
				break;
			case 'xls':
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
				break;
			default:
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
		}
		//设置宽度
// 		$objSheet->mergeCells("A1:E2");
// 		$objSheet->setCellValue("A1", $title);
// 		$objSheet->getStyle('A1')->getFont()->setSize(26);
// 		$objSheet->getStyle('A1')->getFont()->setBold(true);
// 		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			
		$objSheet->getColumnDimension('A')->setWidth(20);
		$objSheet->getColumnDimension('B')->setWidth(20);
		$objSheet->getColumnDimension('C')->setWidth(20);
		$objSheet->getColumnDimension('D')->setWidth(20);
		$objSheet->getColumnDimension('E')->setWidth(20);
		$objSheet->getColumnDimension('F')->setWidth(20);
		$objSheet->getColumnDimension('G')->setWidth(20);
		$objSheet->getColumnDimension('H')->setWidth(20);
		$objSheet->getColumnDimension('I')->setWidth(40);
	
		$objSheet->setCellValue('A1', '商品序号');
		$objSheet->getStyle('A1')->getFont()->setBold(true);
		$objSheet->setCellValue('B1', '商品名称');
		$objSheet->getStyle('B1')->getFont()->setBold(true);
		$objSheet->setCellValue('C1', '编码');
		$objSheet->getStyle('C1')->getFont()->setBold(true);
		$objSheet->setCellValue('D1', '数量');
		$objSheet->getStyle('D1')->getFont()->setBold(true);
		$objSheet->setCellValue('E1', '进货价');
		$objSheet->getStyle('E1')->getFont()->setBold(true);
		$objSheet->setCellValue('F1', '单位');
		$objSheet->getStyle('F1')->getFont()->setBold(true);
		$objSheet->setCellValue('G1', '供货价');
		$objSheet->getStyle('G1')->getFont()->setBold(true);
		$objSheet->setCellValue('H1', '指导价');
		$objSheet->getStyle('H1')->getFont()->setBold(true);
		$objSheet->setCellValue('I1', '供应商');
		$objSheet->getStyle('I1')->getFont()->setBold(true);
		
	
		$rowNum = 2;
		foreach($data as $det){
			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $det['product_id'], false);
			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['product_name'], false);
			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['product_sn'], false);
			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['quantity'], false);
			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['price'], false);
			$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $det['unit_content'], false);
			$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $det['supply_price'], false);
			$this->_genExcelFont($objSheet, "H".$rowNum, "H".$rowNum, $det['guide_price'], false);
			$this->_genExcelFont($objSheet, "I".$rowNum, "I".$rowNum, $det['supplier_name'], false);
			$rowNum++;
		}
			
		ob_end_clean(); // 去掉缓存
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		$objWriter->save('php://output');
	}
	
	/**
	 * @desc 更新供货价，指导价
	 * @author liaojianwen
	 * @date 2017-05-09
	 */
	public function updateGuidePrice($execlResult)
	{
		$tr = Yii::$app->db->beginTransaction();
		try{
			if(is_array($execlResult)){
				foreach ($execlResult as $return){
					$fields =[
						'supply_price'=>round($return['G'],2),
						'guide_price'=>round($return['H'],2),
					];
					$result = ProductDAO::getInstance()->iupdate($fields, "product_id =:pid", [':pid'=>$return['A']]);
					
				}
				$tr->commit();
				return true;
			}
		} catch (\Exception $e){
			
			$tr->rollBack();
			dd($e->getMessage());
			return false;
		}
	}
	
	/**
	 * @desc  读取execl 文件数据更新供应价，指导价
	 * @author liaojianwen
	 * @date 2017-05-11
	 */
	public function updateProductPrice($path, $fileName)
	{
		if ($path == '' || $fileName == '') {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'missing path or filename' );
		}
		$res_execl = $this->read ( $path . $fileName );
		
		if (! $res_execl) {
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', '没有数据，请查找原因');
		}
// 		foreach ( $res_execl as &$res ) {
// 			foreach ( $res as $key => $val ) {
// 				if (empty ( $val )) {
// 					unset ( $res [$key] );
// 				}
// 			}
// 		}
		
		$result = $this->updateGuidePrice ( $res_execl );
		if(!$result){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update fail');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, '');
		
	}
	
	/**
	 * @desc 处理execl文件
	 * @author liaojianwen
	 * @date 2017-05-11
	 */
	private function read($filePath)
	{
		$PHPExcel = new \PHPExcel ();
		$PHPReader = new \PHPExcel_Reader_Excel2007 ();
		if (! $PHPReader->canRead ( $filePath )) {
			$PHPReader = new \PHPExcel_Reader_Excel5 ();
			if (! $PHPReader->canRead ( $filePath )) {
				echo 'no Excel';
				return false;
			}
		}
	
		$PHPExcel = $PHPReader->load ( $filePath );
		/**
		 * 读取excel文件中的第一个工作表
		*/
		$currentSheet = $PHPExcel->getSheet ( 0 );
		/**
		 * 取得最大的列号
		*/
		$allColumn = $currentSheet->getHighestColumn ();
		// 		$allColumn = 'J';
		/**
		 * 取得一共有多少行
		*/
		$allRow = $currentSheet->getHighestRow ();
		$pushArray = array ();
		$nowRow = 0;
		/**
		 * 从第二行开始输出，因为excel表中第一行为列名
		 */
		for($currentRow = 2; $currentRow <= $allRow; $currentRow ++) {
			/**
			 * 从第A列开始输出
			 */
			for($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn ++) {
				// 				$val = $currentSheet->getCellByColumnAndRow ( ord ( $currentColumn ) - 65, $currentRow )->getValue ();//获取计算公式
				$val = $currentSheet->getCellByColumnAndRow ( ord ( $currentColumn ) - 65, $currentRow )->getCalculatedValue ();//获取计算后的值
				/**
				 * ord()将字符转为十进制数
				*/
				if ($currentColumn == 'A' && empty ( $val )) {
					break;
				}
				/**
				 * 如果输出汉字有乱码，则需将输出内容用iconv函数进行编码转换，如下将gb2312编码转为utf-8编码输出
				 */
				if ($val instanceof PHPExcel_RichText) { // 对象文本转换字符串
					$val = $val->__toString ();
				}
				$pushArray [$currentRow] [$currentColumn] = $val;
				// echo iconv('utf-8','gb2312', $val)."\t";
				// }
			}
		}
		return $pushArray;
	}
	
	/**
	 * @desc 同步商品到店铺
	 * @author liaojianwen
	 * @date 2017-08-01
	 */
	private function InitStoreGoods($product_id)
	{
		if(!$product_id){
			return false;
		}
		try{
			$fields =[
				'product_id',
				'product_name',
				'quantity_unit',
				'category_id',
				'description',
				'unit_content',
				'supply_price',
				'guide_price',
				'barcode'
			];
			$conditions = "product_id =:pid and delete_flag=:flag";
			$params =[
				':pid'=>$product_id,
				':flag'=> EnumOther::NO_DELETE
			];
			$pro_select = ProductDAO::getInstance()->iselect($fields, $conditions, $params,'one');
			if(!$pro_select){
				return false;
			}
			$unit_field = [
				'product_unit_id',
				'product_id',
				'unit_type',
				'unit',
				'rate',
				'format',
				'create_time',
				'delete_flag',
			];
			$unit_select = ProductUnitDAO::getInstance()->iselect($unit_field, $conditions, $params,'all');
			if(!$unit_select){
				return false;
			}
			
			$storeUrl = Yii::$app->params ['storeUrl'];
			 
			$key = storeTokenTool::getInstance()->getToken();
			$url = "{$storeUrl}/scm/api/goods-insert";
	
			$dataArr = [
				'product'=>$pro_select,
				'unit' => $unit_select
			];
			$postdata = json_encode($dataArr);
			$result = Curl::curlOption($url, 'POST', $postdata, $key);
			return  $result;
		} catch (\Exception $e){
			return false;
		}
		
	}
	
	/**
	 * @desc 同步商品到商城
	 * @author lizichuan
	 * @date 2017-12-08
	 */
	private function InitShopGoods($product_id)
	{
		if(!$product_id){
			return false;
		}
		try{
			$fields =[
				'product_id',
				'product_name',
				'quantity_unit',
				'supplier_id',
				'category_id',
				'guide_price',
			];
			$conditions = "product_id =:pid and delete_flag=:flag";
			$params =[
				':pid'=>$product_id,
				':flag'=> EnumOther::NO_DELETE
			];
			$product = ProductDAO::getInstance()->iselect($fields, $conditions, $params,'one');
			if(!$product){
				return false;
			}
			
			$shopUrl = Yii::$app->params ['shopUrl'];
			$url = $shopUrl.'/api/goods.php?act=scm&product_id='.$product['product_id'].'&product_name='.urlencode($product['product_name']).'&quantity_unit='.$product['quantity_unit'].'&supplier_id='.$product['supplier_id'].'&category_id='.$product['category_id'].'&guide_price='.$product['guide_price'];
			$key = scmTokenTool::getInstance()->getToken();
			$result = Curl::curlOption($url, 'GET', '', $key);
			return  $result;
		} catch (\Exception $e){
			return false;
		}
	}
	
	/**
	 * @desc 供应链商品单位同步到店铺后台
	 * @author liaojianwen
	 * @date 2017-08-02
	 */
	public function SyncGoodsUnit($product_id)
	{
		if(!$product_id){
			return false;
		}
		try{
			
			$unit_field = [
					'product_unit_id',
					'product_id',
					'unit_type',
					'unit',
					'rate',
					'format',
					'create_time',
					'delete_flag',
			];
			$conditions = "product_id =:pid";
			$params =[
					':pid'=>$product_id,
// 					':flag'=> EnumOther::NO_DELETE
			];
			$unit_select = ProductUnitDAO::getInstance()->iselect($unit_field, $conditions, $params,'all');
			if(!$unit_select){
				return false;
			}
				
			$storeUrl = Yii::$app->params ['storeUrl'];
			
			$key = storeTokenTool::getInstance()->getToken();
			$url = "{$storeUrl}/scm/api/goods-unit-update";
			
			$postdata = json_encode($unit_select);
			$result = Curl::curlOption($url, 'POST', $postdata, $key);
			return  $result;
			
		} catch(\Exception $e){
			return false;
		}
	}
	
	
	/**
	 * @desc 保存商品分拆信息
	 * @param $product_extend 商品信息
	 * @param $remove 删除商品信息
	 * @author liaojianwen
	 * @date 2018-04-09
	 */
	public function saveProductExtend($product_extend, $remove, $product_id)
	{
		if (empty ( $product_extend )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'product_extend is empty' );
		}
		//清掉为空的元素
		foreach ($product_extend as $k=> $det){
			foreach ($det as $j => $deet){
				if($deet ==''){
					unset($product_extend[$k][$j]);
				}
			}
		}
		// 表头信息
		$tr = Yii::$app->db->beginTransaction();
		try{
			//删除的精拆商品
			foreach ($remove as $remove){
				$res_remove = ProductExtendDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "product_extend_id = :det_id", [':det_id'=>$remove['product_extend_id']]);
				if(!$res_remove){
					$tr->rollBack();
					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove product_extend_id:'+$move['product_extend_id'] +'failed');
				}
			}
			foreach ( $product_extend as &$det ) {
				$det['pid'] = $product_id;
				$cond_det = "product_extend_id = :id";
				$param_det = [
						':id' => isset($det ['product_extend_id'])?$det['product_extend_id']:0,
				];
				$res_det = ProductExtendDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
				if (! $res_det) {
					$tr->rollBack();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save product_extend failure' );
				}

			}
				
			$tr->commit();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		}catch (\Exception $e){
			$tr->rollBack();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
		}
	}
	
	/**
	 * @desc  根据id获取分拆商品信息
	 * @author liaojianwen
	 * @date 2018-04-09
	 */
	public function getProductExtendInfo($id)
	{
		if(empty($id)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', ' id is empty');
		}
		$result = ProductExtendDAO::getInstance()->getProductExtendInfo($id);
		if(!$result){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}
}